package com.dreamlin.app.net

import com.dreamlin.app.BuildConfig
import com.dreamlin.app.api.Api
import com.dreamlin.app.net.gson.GsonConverterFactory
import com.google.gson.Gson
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

object NetHelper {

    const val inInner = false
    private val IP = if (inInner) "192.168.4.212" else "124.166.248.6"
    private val contentType = okhttp3.MediaType.get("application/json; charset=UTF-8")
    private var BASE_URL = "http://${this.IP}:${if (inInner) 8066 else 18519}/"
    val DEVICE_LRF_URL =
        "http://${/*if (BuildConfig.DEBUG) "192.168.4.19" else */this.IP}:${if (inInner) 8066 else 18519}/"
    val TOP_SL_URL = "http://${this.IP}:${if (inInner) 8016 else 18515}/"
    val FILE_URL = "http://${this.IP}:${if (inInner) 8066 else 18519}/upload/uploadFile"
    val TUNNEL_ZYY_URL =
        "http://${this.IP}:${if (inInner) 8036 else 18517}/TunnelData_Service/"
    val TUNNEL_WCS_URL =
        "http://${this.IP}:${if (inInner) 8076 else 18520}/TunnelData_Service/"
    val TUNNEL_TJQ_URL =
        "http://${this.IP}:${if (inInner) 8026 else 18516}/"
    val TUNNEL_KPI = "http://${this.IP}:${if (inInner) 8116 else 18522}/kpi/"

    val api: Api by lazy {
        create<Api>(BASE_URL)
    }

    private var dynamicApi: Api? = null

    inline fun <reified T> create(baseUrl: String): T {
        return RetrofitHelper.newRetrofit(baseUrl).create(T::class.java)
    }

    fun setServer(url: String) {
        if (dynamicApi == null)
            dynamicApi = RetrofitHelper.newRetrofit(url).create(Api::class.java)
    }

    fun applyBody(params: Any): RequestBody {
        return RequestBody.create(contentType, Gson().toJson(params))
    }

}

object RetrofitHelper {

    private val mClient: OkHttpClient

    init {
        val builder = OkHttpClient.Builder()
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .callTimeout(10, TimeUnit.SECONDS)
        /**
         * add custom interceptor at here
         */
        /*.addInterceptor()*/
        if (BuildConfig.DEBUG) {
            val httpLoggingInterceptor = HttpLoggingInterceptor()
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            builder.addInterceptor(httpLoggingInterceptor)
        }
        mClient = builder.build()
    }

    fun newRetrofit(baseUrl: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(mClient)
            .build()
    }

}